package com.ds.dsm.editor.action;

import com.ds.config.ResultModel;
import com.ds.context.JDSActionContext;
import com.ds.editor.ESDEditor;
import com.ds.editor.cmd.ESDChrome;
import com.ds.enums.db.MethodChinaName;
import com.ds.esd.custom.annotation.CustomAnnotation;
import com.ds.esd.custom.api.annotation.APIEventAnnotation;
import com.ds.esd.custom.api.enums.RequestPathEnum;
import com.ds.esd.custom.toolbar.CodeEditorTools;
import com.ds.esd.dsm.DSMFactory;
import com.ds.esd.dsm.DSMInst;
import com.ds.esd.dsm.enums.DSMType;
import com.ds.esd.dsm.gen.GenJava;
import com.ds.esd.dsm.java.JavaSrcBean;
import org.openqa.selenium.chrome.ChromeDriver;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.util.Arrays;
import java.util.List;

public class BaseEditorTools extends CodeEditorTools {


    @MethodChinaName(cname = "")
    @RequestMapping(method = RequestMethod.POST, value = "dsmBuildAction")
    @CustomAnnotation(imageClass = "xuicon spafont spa-icon-debug1", caption = "编译", index = 5, tips = "编译")
    @APIEventAnnotation(customRequestData = {RequestPathEnum.form, RequestPathEnum.ctx})
    public @ResponseBody
    ResultModel<Boolean> dsmBuildAction(String projectName, String dsmId, DSMType dsmType, String filePath) {
        ResultModel<Boolean> result = new ResultModel<Boolean>();
        try {
            GenJava genJava = GenJava.getInstance(projectName);
            DSMInst dsmInst = DSMFactory.getInstance().getDSMInst(dsmId, dsmType);
            File file = new File(filePath);

            JavaSrcBean javaSrcBean = dsmInst.getJavaSrcByPath(filePath);
            if (javaSrcBean != null) {
                List<Class> classList = DSMFactory.getInstance().dynCompile(dsmInst, Arrays.asList(javaSrcBean), null);
                for (Class clazz : classList) {
                    System.out.println(clazz.getAnnotations());
                }
            }
//            } else {
//                JavaPackage javaPackage = dsmInst.getPackageByFile(file.getParentFile());
//                genJava.compileDsmInst(javaPackage, getCurrChromeDriver());
//            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public ESDChrome getCurrChromeDriver() {
        Object handleId = JDSActionContext.getActionContext().getParams("handleId");
        ChromeDriver chrome = null;
        if (handleId != null) {
            chrome = ESDEditor.getInstance().getChromeDriverById(handleId.toString());
        }
        if (chrome == null) {
            chrome = ESDEditor.getInstance().getCurrChromeDriver();
        }
        return new ESDChrome(chrome);
    }


}
